package com.jerry.consumer.controller;

import com.jerry.common.bean.User;
import com.jerry.consumer.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/shop/user")
public class UserController {

	@Value("${provider.userUrl}")
	private String userUrl;

	@Autowired
	private DiscoveryClient discoveryClient;

	@Autowired
	private UserClient userClient;

	//查询用户列表
	@SuppressWarnings("unchecked")
	@GetMapping("/list")
	public List<User> getUserList() {
		ServiceInstance instance = discoveryClient.getLocalServiceInstance();
		List<User> userList = userClient.list();
		for (User user : userList) {
			user.setHost(instance.getHost());
			user.setPort(instance.getPort());
			user.setServerId(instance.getServiceId());
			System.out.println("consumer === user === "+user);
		}
		return userList;
	}
		
	//根据id查询用户
	@GetMapping("/get/{id}")
	public User getUser(@PathVariable("id") Long id) {
		ServiceInstance instance = discoveryClient.getLocalServiceInstance();
		User user = userClient.get(id);
		user.setHost(instance.getHost());
		user.setPort(instance.getPort());
		user.setServerId(instance.getServiceId());
		System.out.println("provider === user === "+user);
		return user;
	}

	//增加一个用户
	@GetMapping("/add")
	public boolean addUser(User user) {
		return userClient.add(user);
	}
	
	//增加一个用户
	@GetMapping("/update")
	public boolean updateUser(User user) {
		return userClient.update(user);
	}
	
	//删除一个用户
	@GetMapping("/delete/{id}")
	public void deleteUser(@PathVariable("id") Long id) {
		userClient.delete(id);
	}

	//查询provider-user的实例信息
	@GetMapping("/userInstance")
	public List<ServiceInstance> userInstance() {
		return this.discoveryClient.getInstances("provider-user");
	}


}
